package com.ptone.messagecenter.common.base;


import com.alibaba.fastjson.JSON;
import lombok.Data;

import java.util.Objects;
import java.util.Optional;

@Data
public class Result<E> {
    private Integer status;
    private Integer code;
    private String message;
    private Object data;

    public E getData() {
        return (E) data;
    }


    public Result() {

    }

    private Result(Object data) {
        this.code = ErrCode.OK.code;
        this.status = 200;
        this.message = ErrCode.OK.message;
        this.data = data;
    }

    private Result(ErrCode errCode, Object data) {
        this.code = errCode.code;
        this.status = errCode.code;
        this.message = errCode.message;
        this.data = data;
    }

    /**
     * 自动判断
     *
     * @param tuple2
     * @return
     */
    public static Result end(Tuple2 tuple2) {
        if (Objects.isNull(tuple2))
            return fail();
        if (tuple2.rightNotNull() && tuple2.right() instanceof ErrCode)
            return new Result((ErrCode) tuple2.right(), null);
        return new Result(Optional.ofNullable(tuple2.left()).orElse(""));
    }

    /**
     * 成功
     *
     * @return
     */
    public static Result success() {
        return new Result(true);
    }

    /**
     * 成功
     *
     * @return
     */
    public static <T> Result<T> success(T obj) {
        return new Result<T>(obj);
    }

    /**
     * 失败
     *
     * @return
     */
    public static Result fail() {
        return new Result(ErrCode.SYSTEM_ERROR, null);
    }

    public static Result fail(ErrCode errCode) {
        return new Result(errCode, null);
    }

    public static Result fail(ErrCode errCode, Object data) {
        return new Result(errCode, data);
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }

    public String messageJson() {
        return JSON.toJSONString(new ErrCode(this.status, this.message));
    }

    public String dataJson() {
        return JSON.toJSONString(this.data);
    }
}
